package com.doge.service.admin.comment;

import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.pojo.comment.Comment;
import com.doge.bean.pojo.comment.CommentExample;
import com.doge.exception.Delete502Exception;
import com.doge.mapper.CommentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: project2-wechat-mall
 * @description:
 * @author: 305905917@qq.com
 * @create: 2021-11-30 23:01
 **/
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentMapper commentMapper;

    @Override
    public BaseData list(BaseParam baseParam, Integer userId, Integer valueId) {
        //分页
        if (baseParam.getLimit() != 0) {
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        }

        //设置条件查询
        CommentExample example = new CommentExample();
        CommentExample.Criteria criteria = example.createCriteria();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (valueId != null) {
            criteria.andValueIdEqualTo(valueId);
        }
        if (baseParam.getSort() != null || baseParam.getOrder() != null) {
            example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }
        criteria.andDeletedEqualTo(false);
        List<Comment> comments = commentMapper.selectByExample(example);

        PageInfo info = new PageInfo(comments);
        long total = info.getTotal();
        return BaseData.list(comments, total);

    }

    @Override
    public void delete(Comment comment) throws Delete502Exception {
        CommentExample example = new CommentExample();
        example.createCriteria().andUserIdEqualTo(comment.getUserId()).andIdEqualTo(comment.getId()).andDeletedEqualTo(false);
        comment.setDeleted(true);
        int i = commentMapper.updateByExampleSelective(comment, example);
        if (i != 1)
            throw new Delete502Exception("评论删除失败！");
    }
}
